//
//  GridTreeNodeHelper.swift
//  grid-ios-app
//
//  Created by wondertek on 2024/5/20.
//

import Foundation

class GridTreeNodeHelper {
    
    /// 单例
    static let shared = GridTreeNodeHelper()
    
    
    //传入普通节点，转换成有父node和level的排序后的Node
    func getSortedNodes(_ groups: [GridTreeNodeModel]) -> [GridTreeNodeModel]  {
        var result: [GridTreeNodeModel] = []
        for item in groups{
            addNode(&result, nil, node: item, currentLevel: 1)
        }
        return result
    }
    
    //过滤出所有可见节点
    func filterVisibleNode(_ nodes: [GridTreeNodeModel]) -> [GridTreeNodeModel] {
        var result: [GridTreeNodeModel] = []
        for item in nodes {
            if item.isRoot() || item.isParentExpand() {
                result.append(item)
            }
        }
        return result
    }
    
    
    
    // 获取根节点集
    func getRootNodes(_ nodes: [GridTreeNodeModel]) -> [GridTreeNodeModel] {
        var root: [GridTreeNodeModel] = []
        for item in nodes {
            if item.isRoot() {
                root.append(item)
            }
        }
        return root
    }
    
    //把一个节点的所有子节点都挂上去
    func addNode(_ nodes: inout [GridTreeNodeModel], _ parentNode: GridTreeNodeModel?, node: GridTreeNodeModel, currentLevel: Int) {
        // 设置等级和父节点-等级是为了前突出
        node.level = currentLevel
        node.parent = parentNode
        nodes.append(node)
    
        if node.isLeaf() {
            return
        }
        if let children = node.children {
            for i in 0 ..< children.count {
                addNode(&nodes,node, node: children[i], currentLevel: currentLevel+1)
            }
        }
        
    }
    
    
    
    
}

